# -*- coding: utf-8 -*-
import binascii
import importlib
import sys
import pickle
from PySide6.QtCore import Signal, QTimer, Qt, QDateTime
from PySide6.QtGui import QShortcut, QKeySequence, QTextCharFormat, QColor, QTextCursor
from PySide6.QtWidgets import QWidget, QMessageBox, QApplication
from loguru import logger

from utils.bytesHelper import SliceBytesSafe
from utils.checksum import hex_string_to_list, get_tcon_checksum, i2c0_get_checksum
from utils.filePathTools import GetFilesWithExtension
from windowUI.checksumUI_ui import Ui_ChecksumForm


class ChecksumWindow(QWidget, Ui_ChecksumForm):
    """
    Checksum计算
    """
    # 声明带一个字典类型参数的信号
    checksumSignal = Signal(dict)

    def __init__(self):
        super().__init__()
        # 加载UI
        self.setupUi(self)
        # 连接信号与槽
        self.SignalConnectInit()
        # 添加快捷键
        self.ShortcutFun()
        # 引入公共程序
        from utils.common import commonProgram
        # 引入配置文件
        self.myConfig = commonProgram.EnableConfigHandler()
        print('TpIntWindow get config Version', self.myConfig.version)
        # 引入可控串口信息窗口
        # self.serialPortWin = commonProgram.EnableFt4222(winSignal=self.checksumSignal,
        #                                                RecvFt4222Data=self.RecvFt4222Data)
        # 显示窗口
        # self.serialPortWin.show()

    def CleanupSelf(self):
        """
        清理当前窗口并关闭，由其他其他程序调用
        :return:
        """
        try:
            self.close()  # 关闭当前窗口
            self.deleteLater()  # 释放子窗口资源
            print("TpIntWindow.__del__.ok")
        except Exception as err:
            print("TpIntWindow.__del__.error", err)

    def SignalConnectInit(self):
        """
        连接来自UI对象的信号与槽
        :return:
        """
        self.btnHandExec.clicked.connect(self.BtnHandExecFun)

    def BtnHandExecFun(self):
        timeStr = QDateTime.currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")
        self.UIPrintFun(strData=timeStr, typeValue='>>> >>> >>>', statusColor='cyan')
        algorithm = self.comboBoxAlgorithm.currentText().strip()
        self.UIPrintFun(strData=algorithm, typeValue='算法选择: ')
        iic_data = self.plainTextEditIICData.toPlainText().strip()
        if len(iic_data) < 1:
            QMessageBox.warning(self, "空数据", f"请输入要计算的内容！--> {iic_data}")
            return None
        self.UIPrintFun(strData=iic_data, typeValue='数据: ')
        self.UIPrintFun(strData=len(iic_data.split()), typeValue='长度: ')
        if 'TCON' in algorithm:
            intListData = hex_string_to_list(iic_data)
            # 调用计算函数并获取校验和
            checksum = get_tcon_checksum(intListData)
            dataStr = iic_data + f" {checksum:02X}"
            self.UIPrintFun(strData=f"{checksum:02X}", typeValue='checksum: ', statusColor='red')
            self.UIPrintFun(strData=dataStr, typeValue='目标数据: ', statusColor='green')
        else:
            intListData = hex_string_to_list(iic_data)
            # 调用计算函数并获取校验和
            checksum = i2c0_get_checksum(intListData)
            dataStr = iic_data + f" {checksum:02X}"
            self.UIPrintFun(strData=f"{checksum:02X}", typeValue='checksum: ', statusColor='red')
            self.UIPrintFun(strData=dataStr, typeValue='目标数据: ', statusColor='green')

    def ShortcutFun(self):
        """
        快捷键 F11 全屏
        快捷键 F5 清屏
        :return:
        """
        # 快捷键 F11
        self.screenStatus = 'Normal'
        screenShortcut = QShortcut(QKeySequence(Qt.Key_F11), self)
        screenShortcut.activated.connect(self.WindowSizeFun)
        self.setToolTip('全屏与退出全屏：\n               双击 或者 F11')
        # 快捷键 F5
        # screenShortcut2 = QShortcut(QKeySequence(Qt.Key_F5), self)
        # screenShortcut2.activated.connect(self.CleanFun)

    def WindowSizeFun(self):
        """
        控制窗口尺寸，此处为原大小（最小UI布局）或者全屏
        :return:
        """
        if self.screenStatus == 'Normal':
            self.showFullScreen()
            self.screenStatus = 'FullScreen'
        else:
            self.showNormal()
            self.screenStatus = 'Normal'

    def SendDataHandle(self, dataDict: dict):
        """
        发送信号或数据处理函数
        :param dataDict:
        :return:
        """
        # 发送信号处理
        dataObj = dataDict.get('data', '')
        typeValue = dataDict.get('type', 'null').strip()
        # 本窗口发送数据
        if "send_" in typeValue:
            self.checksumSignal.emit(dataDict)
        elif "read_" in typeValue:
            self.checksumSignal.emit(dataDict)
        elif "ctrl_gpio2" in typeValue:
            self.checksumSignal.emit(dataDict)
        elif "read_gpio" in typeValue:
            self.checksumSignal.emit(dataDict)
        elif 'TpInt_to_' in typeValue:
            # logger.info("Plugin窗口发往其他窗口的数据：", typeValue, dataObj)
            self.checksumSignal.emit(dataDict)
        elif typeValue != None:
            logger.info(f"dataObj={dataObj}, typeValue={typeValue}")
        # do something

    def UIPrintFun(self, strData, typeValue=None, statusColor='blue'):
        '''
        界面 textBrowser 显示内容
        '''
        # 创建一个 QTextCharFormat 用于设置文本格式

        status_format = QTextCharFormat()
        status_format.setForeground(QColor(statusColor))  # 设置状态文本颜色为绿色
        status = typeValue

        text_format = QTextCharFormat()
        text_format.setForeground(QColor(0, 0, 0, 255))  # 设置文字说明文本颜色为黑色

        # 在 QTextBrowser 中插入格式化的文本
        cursor = self.textBrowser.textCursor()
        # 插入状态文本并应用格式
        cursor.insertText(" " + status + " ", status_format)
        # 插入文字说明文本并应用格式
        cursor.insertText(str(strData), text_format)
        # 换行
        cursor.insertText('\n')
        # 将光标移动到文本末尾
        cursor.movePosition(QTextCursor.End)
        self.textBrowser.setTextCursor(cursor)

    def RecvFt4222Data(self, dictData: dict):
        """
        用于接收串口控制窗口发过来的信号或数据
        :param dictData:
        :return:
        """
        self.RecvDataHandle(dictData)

    def RecvDataHandle(self, dataDict: dict):
        """
        处理串口控制窗口发过来的信号或数据
        :param dataDict:
        :return:
        """
        dataObj = dataDict.get('data', None)
        typeValue = dataDict.get('type', 'null').strip()
        optionsDict = dataDict.get('options', {})
        # 收到信号
        if 'TpInt_to_' in typeValue:
            return
        if typeValue == 'status_serial':
            if dataObj == "Serial_Window_Showed":
                pass
            elif dataObj == "Serial_Window_Closed":
                pass
        elif typeValue == 'level_gpio':
            pass
        elif typeValue == 'send_hex':
            pass
        elif typeValue == 'read_hex':
            pass
        elif typeValue == 'rece_protobuf':
            pass
        elif typeValue == 'rece_hex':
            pass
        elif typeValue == 'rece_ascii':
            pass
        elif '_to_TpInt' in typeValue:
            logger.info("收到其他窗口发往Plugin窗口的数据：", typeValue, dataObj)
        # 其他情况
        elif typeValue != None:
            logger.info(f"{typeValue} \t {dataObj}")
        # do something

    def closeEvent(self, event):
        """
        防止误触关闭程序
        :param event:
        :return:
        """
        # 创建一个确认退出的对话框
        reply = QMessageBox.question(
            self, "Confirmation", "Are you sure you want to exit?",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, QMessageBox.StandardButton.No
        )
        if reply == QMessageBox.StandardButton.Yes:
            self.CleanupSelf()
            # 用户确认退出，关闭应用
            event.accept()
        else:
            event.ignore()


# 程序入口，测试当前插件文件使用
if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWindow = ChecksumWindow()
    myWindow.show()
    sys.exit(app.exec())
